package com.example.controller;

import com.example.entity.User;
import com.example.service.ShopCartService;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

    private final UserService userService; // 确保使用构造器注入

    // 推荐使用构造器注入
    public LoginController(UserService userService) {
        this.userService = userService;
    }

    @PostMapping("/login")
    public String loginSubmit(
            @RequestParam String username,
            @RequestParam String password,
            HttpSession session,
            Model model) {

        try {
            // 1. 参数校验
            if (username == null || username.trim().isEmpty() ||
                    password == null || password.trim().isEmpty()) {
                model.addAttribute("error", "用户名和密码不能为空");
                return "login";
            }

            // 2. 调用服务层（确保userService不为null）
            User user = userService.login(username, password);

            if (user != null) {
                // 3. 设置session属性
                session.setAttribute("userid", user.getId());
                session.setAttribute("username", user.getUsername());
                return "redirect:/home";
            } else {
                model.addAttribute("error", "用户名或密码错误");
                return "login";
            }
        } catch (Exception e) {
            // 4. 异常处理
            model.addAttribute("error", "登录异常，请稍后重试");
            return "login";
        }
    }
}